import styles from '../styles.less';
import {Access, connect, useAccess} from 'umi';
import {App, Button, Col, DatePicker, Form, Modal, Pagination, Popover, Row, Select, Space, Table} from 'antd';
import locale from 'antd/es/date-picker/locale/zh_CN';
import {useCallback, useEffect, useState} from 'react';
import {ExclamationCircleFilled} from '@ant-design/icons';
import {formatRangeDate, nowrapColumns} from "@/utils/utils";
import ExecLog from "./ExecLog";

const {RangePicker} = DatePicker;

const LogTable = (props) => {

  const {dispatch, loading, dataTable, submitting} = props;
  const {logTable, setLogTable} = props.data;
  const {modal} = App.useApp();
  const [execLog, setExecLog] = useState(undefined);

  const [form] = Form.useForm();
  const access = useAccess();
  const [tablePayload, setTablePayload] = useState({page: 1, size: 10, param: {}});

  /* 取消操作 */
  function onCancel() {
    setLogTable(undefined);
    dispatch({type: 'XxlJobLog/chgDataTable', payload: {total: 0, list: []}});
    onReset();
  }

  /* 搜索重置 */
  function onReset() {
    form.resetFields();
    setTablePayload({...tablePayload, page: 1, param: {}});
  }

  /* 搜索 */
  function onSearch(values) {
    if (values.createTime) {
      let {start, end} = formatRangeDate(values.createTime);
      values.createTimeStart = start;
      values.createTimeEnd = end;
      values.createTime = undefined;
    }
    setTablePayload({...tablePayload, page: 1, param: {...values}});
  }

  /* 获取列表 */
  const getAllByPage = useCallback((payload) => {
    dispatch({
      type: 'XxlJobLog/getAllByPage',
      payload: payload,
    });
  }, [dispatch]);

  /* 查询监听 */
  useEffect(() => {
    tablePayload.param.jobId = logTable?.data?.id ?? -1;
    tablePayload.param.jobGroup = logTable?.data?.jobGroup ?? -1;
    getAllByPage(tablePayload);
  }, [getAllByPage, tablePayload, logTable]);

  /* 终止任务 */
  function kill(e, record) {
    e.preventDefault();
    if (!submitting) {
      modal.confirm({
        title: '提示',
        icon: <ExclamationCircleFilled/>,
        content: '是否确定终止任务？',
        okText: "确认",
        cancelText: "取消",
        onOk() {
          dispatch({
            type: 'XxlJobLog/kill',
            payload: record.id,
            callback: () => {
              setTablePayload({...tablePayload, page: 1, param: {}});
            },
          });
        },
      });
    }
    return false;
  }

  function onExecLog(id) {
    setExecLog({
      visible: true,
      title: '调度日志',
      data: id,
    });
  }

  const columns = [
    {
      title: '序号',
      width: 70,
      align: 'center',
      render: ({}, {}, index) => (
        <span>
          {(tablePayload.page - 1) * tablePayload.size + index + 1}
        </span>
      ),
    },
    {
      title: '调度时间',
      dataIndex: 'triggerTime',
      ellipsis: true,
      align: 'center',
      render: (_, record) => {
        return (
          <span>{record.triggerTime ? record.triggerTime : '-'}</span>
        );
      },
    },
    {
      title: '调度结果',
      dataIndex: 'triggerCode',
      align: 'center',
      render: (_, record) => {
        switch (record.triggerCode) {
          case 200:
            return (
              <span style={{color: 'blue'}}>成功</span>
            );
          case 500:
            return (
              <span style={{color: 'red'}}>失败</span>
            );
          default:
            return (
              <span>-</span>
            );
        }
      },
    },
    {
      title: '调度日志',
      dataIndex: 'triggerMsg',
      align: 'center',
      width: 120,
      render: (_, record) => {
        return (
          <Popover content={<div dangerouslySetInnerHTML={{__html: record.triggerMsg}}/>} title='调度日志'
                   trigger='hover'>
            <span style={{color: '#0958d9'}}>查看</span>
          </Popover>
        );
      },
    },
    {
      title: '执行时间',
      dataIndex: 'handleTime',
      ellipsis: true,
      align: 'center',
      render: (_, record) => {
        return (
          <span>{record.handleTime ? record.handleTime : '-'}</span>
        );
      },
    },
    {
      title: '执行结果',
      dataIndex: 'handleCode',
      align: 'center',
      render: (_, record) => {
        switch (record.handleCode) {
          case 200:
            return (
              <span style={{color: 'blue'}}>成功</span>
            );
          case 500:
            return (
              <span style={{color: 'red'}}>失败</span>
            );
          case 502:
            return (
              <span style={{color: 'red'}}>失败(超时)</span>
            );
          default:
            return (
              <span>-</span>
            );
        }
      },
    },
    {
      title: '调度日志',
      dataIndex: 'triggerCode',
      align: 'center',
      render: (_, record) => {
        switch (record.triggerCode) {
          case 200:
            return (
              <span style={{color: '#0958d9'}} onClick={() => {
                onExecLog(record.id);
              }}>查看</span>
            );
          default:
            return (
              <span>-</span>
            );
        }
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      align: 'center',
      width: 120,
      render: (_, record) => {
        return (
          <Space size='small'>
            {(record.triggerCode === 200 || record.handleCode !== 0) && record.handleCode === 0 && (
              <Access accessible={access?.xxlJob_log_kill ?? false}>
                <a onClick={e => kill(e, record)}>终止任务</a>
              </Access>
            )}
          </Space>
        );
      },
    },
  ];

  return (
    <Modal
      title={logTable ? logTable.title : ''}
      open={logTable ? logTable.visible : false}
      onCancel={onCancel}
      forceRender={true}
      width={1200}
      footer={null}
    >
      <ExecLog data={{execLog, setExecLog}}/>
      <Form form={form} labelAlign={'left'} labelCol={{span: 6}} className={styles.mySearchForm} onFinish={onSearch}>
        <Row gutter={64}>
          <Col span={8}>
            <Form.Item name={`logStatus`} label={`执行结果`}>
              <Select placeholder='请选择执行结果'>
                <Select.Option value={1}>成功</Select.Option>
                <Select.Option value={2}>失败</Select.Option>
                <Select.Option value={3}>处理中</Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item name={`createTime`} label={`调度时间`}>
              <RangePicker locale={locale} style={{width: '100%'}} format={'YYYY-MM-DD'}/>
            </Form.Item>
          </Col>
          <Col span={8} style={{textAlign: 'right'}}>
            <Button type='primary' htmlType='submit' loading={loading}>
              查询
            </Button>
            <Button style={{margin: '0 8px'}} onClick={() => onReset()}>
              重置
            </Button>
          </Col>
        </Row>
      </Form>
      <div className={styles.myDataTable}>
        <Table
          className={styles.myTable} bordered={false} size={'small'} columns={nowrapColumns(columns, dataTable.list)}
          loading={loading}
          dataSource={dataTable.list} rowKey={'id'}
          pagination={false} scroll={{y: '100%'}}
        />
        <Pagination
          pageSize={tablePayload.size} current={tablePayload.page} total={dataTable.total}
          className={styles.myPagination} size={'small'} hideOnSinglePage={false}
          showTotal={(total) => {
            return `共 ${total} 条记录`;
          }}
          pageSizeOptions={[10]}
          showSizeChanger showQuickJumper={true}
          onChange={(page, pageSize) => {
            setTablePayload({...tablePayload, page: page, size: pageSize});
          }}
        />
      </div>
    </Modal>
  );
};

export default connect(({loading, XxlJobLog}) => {
  return {
    loading: loading.effects['XxlJobLog/getAllByPage'],
    submitting: loading.effects['XxlJobLog/kill'],
    dataTable: XxlJobLog.dataTable,
  };
})(LogTable);
